/**
 * @author hujiangjun 1217437592@qq.com
 * @description 路由控制
 */
import router from "@/router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { getPageTitle } from "@/utils/index";
import { setting } from "@/config/setting";
import { useUserStore } from "@/stores/user";
import { useRoutesStore } from "@/stores/routes";

const {
  authentication,
  loginInterception,
  progressBar,
  routesWhiteList,
  recordRoute,
} = setting;

NProgress.configure({
  easing: "ease",
  speed: 500,
  trickleSpeed: 200,
  showSpinner: false,
});

router.beforeEach(async (to, from) => {
  if (progressBar) NProgress.start();

  const userStore = useUserStore();
  const routesStore = useRoutesStore();

  let hasToken = userStore.accessToken;
  if (!loginInterception) hasToken = true;
  console.log("hasToken", hasToken);

  if (hasToken) {
    if (to.path === "/login") {
      if (progressBar) NProgress.done();
      return { path: "/" };
    } else {
      const hasPermissions =
        userStore.permissions && userStore.permissions.length > 0;
      console.log("hasPermissions", hasPermissions);
      // const hasPermissions = true
      if (hasPermissions) {
        return true;
      } else {
        try {
          let permissions;
          if (!loginInterception) {
            //settings.js loginInterception为false时，创建虚拟权限
            await userStore.setPermissions(["admin"]);
            permissions = ["admin"];
          } else {
            permissions = await userStore.getUserInfo();
          }

          let accessRoutes = [];
          if (authentication === "intelligence") {
            accessRoutes = await routesStore.setRoutes(permissions);
          } else if (authentication === "all") {
            accessRoutes = await routesStore.setAllRoutes();
            console.log("accessRoutes", accessRoutes);
          }
          accessRoutes.forEach((item) => {
            router.addRoute(item);
          });
          return { ...to, replace: true };
        } catch {
          await userStore.resetAccessToken();
          if (progressBar) NProgress.done();
          return false;
        }
      }
    }
  } else {
    // 免登录路由
    if (routesWhiteList.indexOf(to.path) !== -1) {
      return true;
    } else {
      if (recordRoute) {
        if (progressBar) NProgress.done();
        return `/login?redirect=${to.path}`;
      } else {
        if (progressBar) NProgress.done();
        return "/login";
      }
    }
  }
  document.title = getPageTitle(to.meta.title);
});

router.afterEach(() => {
  if (progressBar) NProgress.done();
});
